package com.runshu.runshuwulian.base;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hyphenate.easeui.mwidget.dialog.v3.TipDialog;
import com.hyphenate.easeui.mwidget.dialog.v3.WaitDialog;
import com.runshu.runshuwulian.MApplication;
import com.runshu.runshuwulian.R;
import com.runshu.runshuwulian.base.net.ApiService;
import com.runshu.runshuwulian.base.net.RetrofitFactory;
import com.runshu.runshuwulian.ui.activity.MainActivity;
import com.runshu.runshuwulian.utils.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public abstract class BaseActivity extends AppCompatActivity {
    private Unbinder unbinder;
    protected InputMethodManager inputMethodManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        if (isLightBar())
            StatusBarUtil.StatusBarLightMode( this );
        if (useEventBus()) {
            EventBus.getDefault().register( this );
        }
        if (setContentViewResId() != 0)
            setContentView( setContentViewResId() );
//        SystemBarManager.fullScreen( this );
        unbinder = ButterKnife.bind( this );
        initView( savedInstanceState );
        imOnCreate();

    }

    public ApiService api() {
        return RetrofitFactory.getInstence().API();
    }

    public RequestBody getRequestBody(JSONObject jsonObject) {
        return RequestBody.create( MediaType.parse( "application/json; charset=utf-8" ), jsonObject.toString() );
    }

    private void imOnCreate() {
        if (!isTaskRoot()) {
            Intent intent = getIntent();
            String action = intent.getAction();
            if (intent.hasCategory( Intent.CATEGORY_LAUNCHER ) && action.equals( Intent.ACTION_MAIN )) {
                finish();
                return;
            }
        }
        inputMethodManager = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE );

    }

    protected boolean isLightBar() {
        return true;
    }

    protected boolean useEventBus() {
        return false;
    }

    protected void openActivity(String action) {
//        openActivity(action, null);
    }

    public void showEnsureDialog(String message) {

    }

    public void showShortToast(String msg) {
        Toast.makeText( this, msg, Toast.LENGTH_SHORT ).show();
    }

    protected abstract int setContentViewResId();

    protected void initView(@Nullable Bundle savedInstanceState) {
    }

    @Override
    public void startActivity(Intent intent) {
        if (MainActivity.class.getName().equals( intent.getComponent().getClassName() )) {
            intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK );
        }
        super.startActivity( intent );
    }

    public void startActivityByAlphAnimAndFinish(Class activity) {

        startActivity( new Intent( this, activity ) );
        finish();
        overridePendingTransition( R.anim.fade_imme_in, R.anim.fade_out );
    }

    public void startActivityByAlphAnim(Class activity) {
        startActivity( new Intent( this, activity ) );
        overridePendingTransition( R.anim.fade_imme_in, R.anim.fade_out );
    }

    public void startActivityByAlphAnim(Class activity, Bundle bundle) {
        Intent intent = new Intent( this, activity );
        intent.putExtras( bundle );
        startActivity( intent );
        overridePendingTransition( R.anim.fade_imme_in, R.anim.fade_out );
    }

    //todo 增加动画方法
    public void startActivityByDefaultAnim(Class activity) {
        startActivity( new Intent( this, activity ) );
//        overridePendingTransition( com.hyphenate.easeui.R.anim.slide_in_from_left, com.hyphenate.easeui.R.anim.slide_out_to_right );
        overridePendingTransition( R.anim.slide_in_from_right, R.anim.slide_out_to_left );

    }

    //todo 增加动画方法
    public void startActivityByDefaultAnim(Intent intent) {
        startActivity( intent );
//        overridePendingTransition( com.hyphenate.easeui.R.anim.slide_in_from_left, com.hyphenate.easeui.R.anim.slide_out_to_right );
        overridePendingTransition( R.anim.slide_in_from_right, R.anim.slide_out_to_left );

    }

    //todo
    public void finishByDefaultAnim() {
        finish();
//        overridePendingTransition( com.hyphenate.easeui.R.anim.slide_out_to_left, com.hyphenate.easeui.R.anim.slide_in_from_right );
        overridePendingTransition( R.anim.slide_in_from_left, R.anim.slide_out_to_right );
//        overridePendingTransition( com.hyphenate.easeui.R.anim.slide_in_from_right, com.hyphenate.easeui.R.anim.slide_out_to_left );

    }
//    ProgressDialog progressDialog;

    public void showProgressDialog(String message, Boolean cancelable) {
        WaitDialog.show( this, message ).setCancelable( cancelable );
//        if (progressDialog == null)
//            progressDialog = new ProgressDialog( this );
//        progressDialog.setProgressStyle( ProgressDialog.STYLE_SPINNER );//转盘
//        progressDialog.setCancelable( cancelable );
//        progressDialog.setCanceledOnTouchOutside( false );
//        progressDialog.setMessage( message );
//        progressDialog.show();
    }

    public void showDefaultProgressDialog(boolean canCelable) {
        WaitDialog.show( this, "加载中" ).setCancelable( canCelable );
    }

    public TipDialog showDefaultProgressDialog(boolean canCelable, String msg) {
        return WaitDialog.show( this, msg ).setCancelable( canCelable );
    }

    public void dissmissProgressDialog() {
        WaitDialog.dismiss();
    }

    public void dissmisProgressDialog() {
        WaitDialog.dismiss();
    }


    public BaseActivity self() {
        return BaseActivity.this;
    }
    //IM

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void back(View view) {
        finishByDefaultAnim();
    }

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow( getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS );
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard( v, ev )) {
                hideKeyboard( v.getWindowToken() );
            }
        }
        return super.dispatchTouchEvent( ev );
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow( l );
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE );
            im.hideSoftInputFromWindow( token, InputMethodManager.HIDE_NOT_ALWAYS );
        }
    }

    @Override
    protected void onDestroy() {
        if (unbinder != null) unbinder.unbind();
        EventBus.getDefault().unregister( this );
        super.onDestroy();
    }
}
